package com.example.juc.kkb.synchronizedandlock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ShareData {
    private int number = 1;//A:1,B:2,C:3
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    //A线程打印5次
    public void printC1() {
        lock.lock();
        try {
            //1.判断
            if (number != 1) {
                c1.await();
            }
            //2.⼲活
            for (int i = 0; i < 5; i++) {

                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            //3.通知 B， 第2个
            number = 2;
            c2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //B线程打印10次
    public void printC2() {
        lock.lock();
        try {
            //1.判断
            if (number != 2) {
                c2.await();
            }
            //2.⼲活
            for (int i = 0; i < 10; i++) {

                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            //3.通知 C， 第3个
            number = 3;
            c3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //C线程打印15次
    public void printC3() {
        lock.lock();
        try {
            //1.判断
            if (number != 3) {
                c3.await();
            }
            //2.⼲活
            for (int i = 0; i < 15; i++) {

                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            //3.通知 A， 第1个
            number = 1;
            c1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}